package com.cat.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cat.admin.service.SysUserService;
import com.cat.common.entity.SysUser;
import com.cat.common.entity.UserInfo;
import com.cat.common.exception.BaseException;
import com.cat.common.model.Result;
import com.cat.common.util.ExcelUtils;
import com.cat.common.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dd-cat
 * @version 1.0
 * @date 2020-10-12 17:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Api(value = "user", tags = "用户模块")
public class SysUserController {
    private final SysUserService userService;

    @GetMapping("page")
    public IPage<SysUser> page(Page<SysUser> page, SysUser user) {
        return userService.page(page, Wrappers.query(user));
    }

    /**
     * 获取指定用户全部信息
     *
     * @return 用户信息
     */
    @GetMapping("/info/{username}")
    public UserInfo info(@PathVariable String username) {
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
        if (user == null) {
            throw new BaseException(String.format("用户信息为空 %s", username));
        }
        return userService.getUserInfo(user);
    }

    @GetMapping("list")
    public List<SysUser> list(SysUser user) {
        return userService.list(Wrappers.query(user));
    }

    /**
     * 通过ID查询
     *
     * @param id ID
     */
    @GetMapping("/{id}")
    public SysUser getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    /**
     * 添加
     *
     * @param user 实体
     */
    @PostMapping
    public boolean save(@Valid @RequestBody SysUser user) {
        return userService.save(user);
    }

    /**
     * 删除
     *
     * @param ids ids
     */
    @DeleteMapping("/{ids}")
    public boolean removeByIds(@PathVariable List<Long> ids) {
        return userService.removeByIds(ids);
    }

    /**
     * 编辑
     *
     * @param sysUser 实体
     */
    @PutMapping
    public boolean update(@Valid @RequestBody SysUser sysUser) {
        UserInfo user = SecurityUtils.getUser();
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUser.setUpdateBy(user.getUsername());
        if (StrUtil.isNotBlank(sysUser.getPassword())) {
            sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        }
        return userService.updateById(sysUser);
    }

    /**
     * 导出
     */
    @PostMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        ExcelUtils.exportExcel(userService.list(), null, "用户列表", SysUser.class, "SysUser", response);
    }

    /**
     * 导入
     */
    @PostMapping("/import")
    public Object importData(@RequestParam("file") MultipartFile file) throws Exception {
        List<SysUser> list = ExcelUtils.importExcel(file, 0, 1, SysUser.class);
        if (list.size() > 0) {
            userService.saveBatch(list);
            return Result.success();
        }
        return Result.fail("excel无数据，导入失败！");
    }

    /**
     * 导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws Exception {
        ExcelUtils.exportExcel(new ArrayList<>(), null, "用户列表", SysUser.class, "SysUser", response);
    }
}
